//
//  MainViewController.m
//  IntelligentHousehold
//
//  Created by wmwMAC on 17/6/23.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "MainViewController.h"

#import "SetViewController.h"//设置
#import "SetPhoneLockRecordViewController.h"

//#import "FMDBHelp.h"
#import "DataBaseManager.h"

#import "AFNetworking.h"


@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self addBtnUI];
    
    
    [[DataBaseManager shareInstance]openDB];
    [[DataBaseManager shareInstance]createTable];
    
    
    
    

    
    [self initiii];
}
-(void)initiii {
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                [self postUnlockCord];
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
               
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self postUnlockCord];

                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self postUnlockCord];

                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
    
}


-(void)addBtnUI{
    
    UIImageView *backImgView = [MyUtil createImageViewFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight) imageName:@"首页copy"];
    [self.view addSubview:backImgView];
    
    
    
    CGFloat btnWeidth = kUIScreenWidth/4;
    UIButton *openBtn = [MyUtil createBtnFrame:CGRectMake(kUIScreenWidth/2-btnWeidth/2, kUIScreenHeight-3*btnWeidth, btnWeidth, btnWeidth) title:@"" bgImage:@"sye_ksan" selectBgImage:@"" image:@"" target:self action:@selector(openBtnCkick)];
    [openBtn setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:openBtn];
    
    UIButton *nameBtn = [MyUtil createBtnFrame:CGRectMake(kUIScreenWidth/2-btnWeidth/2, CGRectGetMaxY(openBtn.frame)+10, btnWeidth, 20) title:@". 点击开锁 ." bgImage:@"" selectBgImage:nil image:@"" target:self action:@selector(openBtnCkick)];
    [nameBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nameBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:nameBtn];
    
    
}

-(void)openBtnCkick{
    
    [[DataBaseManager shareInstance]createTable];
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *telStr = saveDic[@"tell"];
    NSString *lockNumberStr = saveDic[@"locknumber"];
//    lockNumberStr = @"10086";
    NSString *typeStr = [saveDic objectForKey:@"type"];
    if (typeStr.integerValue == 0 || typeStr.integerValue == 1) {
        if (lockNumberStr.length > 3) {
            //给门锁打电话
            NSMutableString* str= [[NSMutableString alloc] initWithFormat:@"telprompt://%@",lockNumberStr];
            // NSLog(@"str======%@",str);
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:^(BOOL success) {
                
                //电话接通
                if (success) {
                    // 获取当前时间
                    NSString *timeStr = [BasePublicMethord getTimeDataPointString];
                    NSLog(@"%@",timeStr);
                    //base64 手机号加密
                    NSData *data = [telStr dataUsingEncoding:NSUTF8StringEncoding];
                    NSString *base64Str = [data base64EncodedStringWithOptions:0];
                    // 存入数据
                    [[DataBaseManager shareInstance] insertTel:base64Str Time:timeStr];
                    
                    [self postUnlockCord];
                }
            }];
            
        }else{
            [MBProgressHUD showText:@"请先设置门锁号码"];
        }

    }else{
        [MBProgressHUD showText:@"当前账号没有权限!"];
    }
 //15707903416
    
           
#pragma mark ------ base64加密 ---------
            
//            NSData *data = [telStr dataUsingEncoding:NSUTF8StringEncoding];
//            NSString *base64Str = [data base64EncodedStringWithOptions:0];
//            NSLog(@"base64Str : %@", base64Str);
            
            // 解密
//            NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Str options:0];
//            NSString *base64Decoded = [[NSString alloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
//            NSLog(@"str : %@", base64Decoded);
            
 
            
        
    
    
    
    
    
    
}

// 通话记录上传
-(void)postUnlockCord{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSArray *lockArr = [[DataBaseManager shareInstance] selectAll];
    
    if (lockArr.count) {
        NSString *url = [NSString stringWithFormat:UNLOCKCORD,RealmName];
        
        NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
        [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
        [parameDic setObject:saveDic[@"token"] forKey:@"token"];
        
        NSString *lockStr = [BasePublicMethord jsonArraytoJsonStr:lockArr];
        [parameDic setObject:lockStr forKey:@"messg"];
        
        NSString *lockNumberStr = saveDic[@"locknumber"];
        NSData *data = [lockNumberStr dataUsingEncoding:NSUTF8StringEncoding];
        NSString *base64Str = [data base64EncodedStringWithOptions:0];
        [parameDic setObject:base64Str forKey:@"locknumber"];
        
        
        [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            
            [[DataBaseManager shareInstance] dropTable];
            
        } failure:^(NSError *error) {
            
        }];
    }
    
    

}
- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options
completionHandler:(void (^ __nullable)(BOOL success))completion{
    
}

-(void)alertAction{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *lockNumberStr = saveDic[@"locknumber"];

    if ([[saveDic objectForKey:@"type"] integerValue] == 0) {
        if (lockNumberStr.length) {
            SetPhoneLockRecordViewController *replyVC = [[SetPhoneLockRecordViewController alloc] init];
            [self.navigationController pushViewController:replyVC animated:YES];
        }else{
            [MBProgressHUD showText:@"请设置门锁号码"];
        }
    }else{
        [MBProgressHUD showText:@"当前账号没有权限!"];
    }
    
    
    
    
    
}
-(void)setItemAction{
    SetViewController *lockSetVC = [[SetViewController alloc] init];
    [self.navigationController pushViewController:lockSetVC animated:YES];
    NSLog(@"setItemAction");
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //导航栏透明
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    //    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;
    
    self.navigationItem.title = @"开锁";
    //导航栏字体设置白色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    UIBarButtonItem *alertItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sye_jl"] style:(UIBarButtonItemStyleDone) target:self action:@selector(alertAction)];
    alertItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = alertItem;
    
    UIBarButtonItem *setItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sy_sz"] style:(UIBarButtonItemStyleDone) target:self action:@selector(setItemAction)];
    setItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = setItem;
    
    /** 修改当前UIViewController的状态栏颜色为白色 */
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    
    //    [self loginData];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
